package com.yuzhihao.writejvm.attributes;

import com.yuzhihao.writejvm.clazz.ClassInfo;
import com.yuzhihao.writejvm.constant.ConstantClassInfo;
import com.yuzhihao.writejvm.constant.ConstantUtf8Info;
import com.yuzhihao.writejvm.format.PrintFormat;
import com.yuzhihao.writejvm.read.Parse;
import lombok.Data;
import lombok.EqualsAndHashCode;
import lombok.extern.log4j.Log4j2;

import java.io.DataInputStream;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

/**
 * 异常属性
 * <a href="https://docs.oracle.com/javase/specs/jvms/se8/html/jvms-4.html#jvms-4.7.5">ExceptionsAttribute</a>
 *
 * @author yzh
 * @since 2021年12月11日11:11:38
 */
@Data
@Log4j2
@EqualsAndHashCode(callSuper = true)
public class ExceptionsAttribute extends Attributes {

    private int number_of_exceptions_u2 = 2;

    private int number_of_exceptions;

    private int index_u2 = 2;

    private List<Integer> indexs = new ArrayList<>();

    public ExceptionsAttribute(String name){
        super();
        super.setAttribute_name(name);
    }

    @Override
    public void parse(DataInputStream dis, ClassInfo ci) {
        this.setCi(ci);
        try {
            super.attribute_length = Parse.byteToInt(super.attribute_length_u4, dis);
            this.number_of_exceptions = Parse.byteToInt(this.number_of_exceptions_u2, dis);

            int i = 0;
            while (i < this.number_of_exceptions){
                indexs.add(Parse.byteToInt(this.index_u2, dis));
                i++;
            }
        } catch (IOException e) {
            log.error(e);
        }
    }

    @Override
    public String print(String print) {
        StringBuilder builder = new StringBuilder();
        builder.append(print).append("Exceptions").append(PrintFormat.COLON).append(System.lineSeparator());
        builder.append(print).append(PrintFormat.EMPTY).append("throws").append(PrintFormat.EMPTY);

        for (Integer index : this.indexs) {
            ConstantClassInfo cci = (ConstantClassInfo)this.getCi().getCp_info().getPools().get(String.valueOf(index));
            builder.append(cci.getConstant()).append(System.lineSeparator());
        }

        return builder.toString();
    }
}
